﻿#include <iostream>
using namespace std;

struct ListNode 
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};
 
class Solution
{
public:
    // 25. K 个一组翻转链表
    ListNode* reverseKGroup(ListNode* head, int k)
    {
        int n = 0;
        ListNode* t = head;
        while (t)
        {
            n++;
            t = t->next;
        }
        n = n / k;

        ListNode* cur = head;
        ListNode rhead;
        ListNode* r = &rhead;
        while (n--)
        {
            int i = k;
            ListNode* prev = cur;
            while (i--)
            {
                ListNode* next = cur->next;
                cur->next = r->next;
                r->next = cur;
                cur = next;
            }
            r = prev;
        }
        r->next = cur;
        return rhead.next;
    }
};

int main()
{
    ListNode* n1 = new ListNode(1);
    ListNode* n2 = new ListNode(2);
    ListNode* n3 = new ListNode(3);
    ListNode* n4 = new ListNode(4);
    ListNode* n5 = new ListNode(5);

    n1->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = n5;

    Solution().reverseKGroup(n1, 2);

    return 0;
}